import os
import wx

from plugins.base import plugin
from debuggerPane import DebuggerPane

class Debugger(plugin.Plugin):
  def __init__(self):
    plugin.Plugin.__init__(self)

  def createPane(self):
    if self._mainFrm is None:
      return None
    pane = DebuggerPane(self._mainFrm)
    return pane

  def createConfigPane(self):
    return None

  def createMenus(self):
    
    if self._mainFrm is None:
      return None
    
    menu = None

    if menu is None:
      menu = []

      # create file menu
      debug_menu = wx.Menu()

      debug_menu_item_run_script = debug_menu.Append(-1, '&Run Script')
      self._mainFrm.Bind(wx.EVT_MENU, self.onRunScript, debug_menu_item_run_script)

      debug_menu_item_run_project = debug_menu.Append(-1, '&Run Project')
      self._mainFrm.Bind(wx.EVT_MENU, self.onRunProject, debug_menu_item_run_project)

      debug_menu_item_stop = debug_menu.Append(-1, '&Stop')
      self._mainFrm.Bind(wx.EVT_MENU, self.onStop, debug_menu_item_stop)

      menu.append(('&Debug', debug_menu))
  
    return menu

  def createToolbar(self):
    return None

  def onRunScript(self, evt):
    if self._pluginMgr is None or self._pane is None:
      evt.Skip()
      return

    pluginInfo = self._pluginMgr.getPluginByName('DocumentManager')
    if pluginInfo is None:
      evt.Skip()
      return

    mod = pluginInfo.getModule()
    if mod is None:
      evt.Skip()
      return

    curDoc = mod.getCurrentDocument()
    if curDoc is None:
      evt.Skip()
      return

    self._pane.runScript(curDoc.getFilename())

  def onRunProject(self, evt):    
    if self._pluginMgr is None or self._pane is None:
      evt.Skip()

    pluginInfo = self._pluginMgr.getPluginByName('ProjectManager')
    if pluginInfo is None:
      evt.Skip()

    mod = pluginInfo.getModule()
    if mod is None:
      evt.Skip()

    mainScript = mod.getMainScript()
    if mainScript is None:
      evt.Skip()

    self._pane.runScript(mainScript)

  def onStop(self, evt):
    if self._pane is None:
      return
    self._pane.stopScript()

instance = None
def getInstance():
  global instance
  if instance is None:
    instance = createInstance()
  return instance

def createInstance():
  return Debugger()